package me.shurufa.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.adapter.SingleChooseAdapter;
import me.shurufa.implement.ItemClickListener;
import me.shurufa.model.Book;
import me.shurufa.model.BookInfoResponse;
import me.shurufa.model.BookResponse;
import me.shurufa.model.Catalog;
import me.shurufa.model.CatalogArrayListResponse;
import me.shurufa.model.SearchBookListResponse;
import me.shurufa.model.SearchBookResponse;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.NetworkConstants;
import me.shurufa.net.RequestServerTask;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.popupwindow.WheelPopWindow;

/**
 * 点击摘书->保存书摘的后续操作
 * 需要注意这个页面是复用的
 * 如果从已经在书架上的书上点击跳转到添加书摘和笔记后再跳转到这个页面
 * 需要把搜索框和下面的换一批横向列表隐藏 同时部分条目要设置不可编辑
 * <p/>
 * 点击完成后需要跳转到完成页面 AddBookCompleteActivity
 * <p/>
 * 注意：需要区分是否含有Book这个对象 如果跳转过来时已经含有book对象了
 * 那么搜索部分隐藏
 *
 * @FileName: me.shurufa.activities.AddDigestActivity.java
 * @author: kHRYSTAL
 * @email: 723526676@qq.com
 * @date: 2016-02-04 00:05
 */
public class AddDigestActivity extends BaseActivity implements View.OnClickListener, ItemClickListener, TextWatcher, TextView.OnEditorActionListener {


    public static final int SCAN_REQUEST_CODE = 5630;

    @Bind(R.id.divider)
    View divider;
    @Bind(R.id.search_edit)
    EditText searchEdit;
    @Bind(R.id.search_clear)
    ImageView searchClear;
    @Bind(R.id.go_qrcode)
    ImageView goQrcode;
    @Bind(R.id.search_bar)
    Toolbar searchBar;
    @Bind(R.id.book_find_recyclerview)
    RecyclerView bookFindRecyclerview;
    @Bind(R.id.exchange_button)
    Button exchangeButton;
    @Bind(R.id.layout_find_layout)
    LinearLayout layoutFindLayout;
    @Bind(R.id.txt_book_name)
    TextView txtBookName;
    @Bind(R.id.book_name_edit)
    TextView bookNameEdit;
    @Bind(R.id.txt_author_name)
    TextView txtAuthorName;
    @Bind(R.id.author_name_edit)
    TextView authorNameEdit;
    @Bind(R.id.txt_publisher_name)
    TextView txtPublisherName;
    @Bind(R.id.publisher_name_edit)
    TextView publisherNameEdit;


    @Bind(R.id.next_layout)
    RelativeLayout nextLayout;
    @Bind(R.id.left_text)
    TextView leftText;
    @Bind(R.id.right_image)
    ImageView rightImage;
    @Bind(R.id.right_text)
    TextView rightText;
    @Bind(R.id.toolbar_divider)
    View toolbarDivider;

//    recyclerview相关
    List<Book> dataList;
    SingleChooseAdapter adapter;
    int page=1;



    private InputMethodManager imm;

    private String mNote;//笔记
    private String mContent;//书摘内容
    private boolean isSend;//发布状态 publish or save

    //commit info

    private long bid;
    private long externalBookId;
    private String pageNumber;


    public String searchKey="";


    private int mSearchType;//搜索类型 用于切换适配器append方法


    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_add_digest;
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);


        mContent = getIntent().getStringExtra(Constants.ARG_DIGEST_CONTENT);
        mNote = getIntent().getStringExtra(Constants.ARG_DIGEST_NOTE);
        isSend = getIntent().getBooleanExtra(Constants.ARG_DIGEST_STATE,true);

//        初始化滚轮控件内容 即目录 如果目录为空 则显示编辑框 否则显示目录
        initUI();
    }

    private void initUI() {
//init toolbar and widget
        imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        titleTextView.setText(getString(R.string.make_digest));

        nextLayout.setOnClickListener(this);

//init recyclerview
            dataList = new ArrayList();
            LinearLayoutManager manager = new LinearLayoutManager(this);
            manager.setOrientation(LinearLayoutManager.HORIZONTAL);
            bookFindRecyclerview.setLayoutManager(manager);
            adapter = new SingleChooseAdapter(this,dataList);
            adapter.setItemClickListener(this);
            bookFindRecyclerview.setAdapter(adapter);

            goQrcode.setOnClickListener(this);
            searchClear.setOnClickListener(this);
            searchEdit.addTextChangedListener(this);
            searchEdit.setOnEditorActionListener(this);
            exchangeButton.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.next_layout:
                if (bid!=0L||externalBookId!=0L) {
                    new RequestServerTask<BookResponse>(BookResponse.class, AddDigestActivity.this, getString(R.string.commit_pls_wait)) {
                        @Override
                        protected String requestServer() {
                            Map<String, Object> params = new HashMap<String, Object>();
                            if (bid != 0L)
                                params.put("bookId", bid);
                            else
                                params.put("externalBookId", externalBookId);
                            params.put("token", Global.currentUser.token);
                            return HttpUtil.post(NetworkConstants.ADD_BOOK_TO_SHELVES, params);
                        }

                        @Override
                        protected void onSuccess(BookResponse result) {
                            if (result.success) {
                                Utils.showToast(R.string.add_to_bookshelves_complete);
                                Intent sendIntent = new Intent(AddDigestActivity.this, AddDigestMenuActivity.class);
                                sendIntent.putExtra(Constants.ARG_BOOK, result.data.toString());
                                sendIntent.putExtra(Constants.ARG_DIGEST_CONTENT, mContent);
                                sendIntent.putExtra(Constants.ARG_DIGEST_STATE, isSend);
                                if (!TextUtils.isEmpty(mNote))
                                    sendIntent.putExtra(Constants.ARG_DIGEST_NOTE, mNote);
                                startActivity(sendIntent);
                            }
                        }
                    }.start();
                }else {
                    Utils.showToast(R.string.book_info_is_empty);
                }
                break;
            case R.id.go_qrcode:
                intent = new Intent(AddDigestActivity.this,QRScanActivity.class);
                startActivityForResult(intent,SCAN_REQUEST_CODE);
                break;
            case R.id.search_clear:
                searchEdit.setText("");
                break;
            case R.id.exchange_button:
                if (mSearchType==Constants.SEARCH_BY_KEYWORD) {
                    page++;
                    refreshAdapterTip();
                    searchByKeyword(searchKey);
                }
                break;
        }
    }

//    private void commitDigestInfoCheckHasMenu() {
//        if (!hasMenu){
//            new RequestServerTask<BaseResponse>(BaseResponse.class,this,getString(R.string.commit_pls_wait)){
//
//                @Override
//                protected String requestServer() {
//                    Map<String,Object> params = new HashMap<String, Object>();
//                    params.put("token",Global.currentUser.token);
//                    params.put("bookId",bookId);
//                    params.put("title",menuName.getText().toString().trim());
//                    params.put("menuOrder", editPart.getText().toString().trim());
//                    return HttpUtil.post(NetworkConstants.ADD_MENU,params);
//                }
//
//                @Override
//                protected void onSuccess(BaseResponse result) {
//                    //TODO setMenuId = result.menuId
//                    mMenuId = 252332;
//                    commitDigest();
//                }
//            }.start();
//        }else {
//            commitDigest();
//        }
//    }
//
//    private void commitDigest() {
//        new RequestServerTask<BaseResponse>(BaseResponse.class,this,getString(R.string.commit_pls_wait)){
//
//            @Override
//            protected String requestServer() {
//                Map<String,Object> params = new HashMap<String, Object>();
//                params.put("bookId",bookId);
//                params.put("token",Global.currentUser.token);
//                params.put("menuId",mMenuId);
//                params.put("pageNumber",pageNumber);
//                params.put("content",mContent);
//                params.put("publishState",isSend?"publish":"save");
//                if (!TextUtils.isEmpty(mNote))
//                    params.put("note",mNote);
//                return HttpUtil.post(NetworkConstants.ADD_DIGEST,params);
//            }
//
//            @Override
//            protected void onSuccess(BaseResponse result) {
//                Intent intent = new Intent(AddDigestActivity.this,AddDigestCompleteActivity.class);
//                intent.putExtra(Constants.ARG_BOOK_TITLE,bookNameEdit.getText().toString());
//                startActivity(intent);
//            }
//        }.start();
//    }

//    private boolean checkCommitInfo() {
//        if (mBook!=null){
//            bookId = mBook.bid;
//            pageNumber = pageNumberEdit.getText().toString().trim();
//            if (TextUtils.isEmpty(pageNumber)){
//                Utils.showToast(R.string.page_number_is_empty);
//                return false;
//            }
//            if (TextUtils.isEmpty(mContent)){
//                Utils.showToast(R.string.digest_content_not_be_empty);
//                return false;
//            }
//        }else {
//            if (bookId == 0L){
//                Utils.showToast(R.string.book_info_is_empty);
//                return false;
//            }
//            pageNumber = pageNumberEdit.getText().toString().trim();
//            if (TextUtils.isEmpty(pageNumber)){
//                Utils.showToast(R.string.page_number_is_empty);
//                return false;
//            }
//            if (TextUtils.isEmpty(mContent)){
//                Utils.showToast(R.string.digest_content_not_be_empty);
//                return false;
//            }
//        }
//
//        if (hasMenu&&mMenuId==0L){
//            Utils.showToast(R.string.menu_info_is_empty);
//            return false;
//        }
//        if (!hasMenu&&TextUtils.isEmpty(editPart.getText().toString().trim())
//                &&TextUtils.isEmpty(menuName.getText().toString().trim())) {
//            Utils.showToast(R.string.part_and_menu_is_empty);
//            return false;
//        }
//        return true;
//    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (intent.getAction().equals(Constants.ACTION_ADD_DIGEST_COMPLETE))
            finish();
    }

    public void refreshAdapterTip(){
        bid=0L;externalBookId=0L;
        adapter.setNotifyTip(-1);
        adapter.notifyDataSetChanged();
        bookNameEdit.setText("");
        authorNameEdit.setText("");
        publisherNameEdit.setText("");
    }

    @Override
    public void onItemClick(View view, Book book, int position) {
        if (adapter!=null){
// modify single choose
            adapter.setNotifyTip(position);
            adapter.notifyDataSetChanged();
// bind widget bookinfo
//            setBookId for commit
            bid = book.bid;
            externalBookId = book.external_book_id;

            if (!TextUtils.isEmpty(book.title))
                bookNameEdit.setText(book.title);
            else bookNameEdit.setText("");
            if (!TextUtils.isEmpty(book.author))
                authorNameEdit.setText(book.author);
            else authorNameEdit.setText("");
            if (!TextUtils.isEmpty(book.publisher))
                publisherNameEdit.setText(book.publisher);
            else publisherNameEdit.setText("");
// search menu
        }
    }


//    Search Edit

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==SCAN_REQUEST_CODE){
            if (resultCode == QRScanActivity.RESULT_CODE){
                exchangeButton.setVisibility(View.GONE);
                refreshAdapterTip();
                String isbn = data.getStringExtra(Constants.EXTRA_SCAN_RESULT);
                if (!TextUtils.isEmpty(isbn)){
                    switchSearchType(Constants.SEARCH_BY_ISBN);
                    searchByISBN(isbn);
                }
            }
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        searchClear.setVisibility(s.length() == 0 ? View.INVISIBLE : View.VISIBLE);
        exchangeButton.setVisibility(View.VISIBLE);
        switchSearchType(Constants.SEARCH_BY_KEYWORD);
    }

    private void switchSearchType(int searchType) {
        mSearchType = searchType;
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH||(event!=null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            switchSearchType(Constants.SEARCH_BY_KEYWORD);
            refreshAdapterTip();
            exchangeButton.setVisibility(View.VISIBLE);
            String text = v.getText().toString();
            //search by keyword method
            searchByKeyword(text);
            imm.hideSoftInputFromWindow(v.getWindowToken() , 0);
            return true;
        }
        return false;
    }

    private void searchByKeyword(String text) {
        if (text.length() == 0) {
            return;
        }
        searchKey = text;
        //搜索 填充到列表上
        new RequestServerTask<SearchBookListResponse>(SearchBookListResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("keyword", searchKey);
                params.put("page", String.valueOf(page));
                params.put("pageSize",4);
                return HttpUtil.post(NetworkConstants.SEARCH_BOOK_BY_KEYWORD, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
            }

            @Override
            protected void onSuccess(SearchBookListResponse result) {
                if (result.data == null || result.data.books == null || result.data.books.length == 0) {
                    Utils.showToast(R.string.no_more_content);
                } else {
                    bindData(result);
                }
            }
        }.start();
    }


    private void searchByISBN(final String text) {
        //将searchByKeyWord初始化
        searchKey="";page=1;
        if (text.length() == 0)
            return;
        new RequestServerTask<SearchBookResponse>(SearchBookResponse.class) {
            @Override
            protected String requestServer() {
                Map<String, Object> params = new HashMap<String, Object>();
                params.put("isbn", text);
                return HttpUtil.post(NetworkConstants.SEARCH_BOOK_BY_ISBN, params);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
            }

            @Override
            protected void onSuccess(SearchBookResponse result) {
                if (result.data.id == 0L) {
                    Utils.showToast(R.string.no_find_book);
                } else {
                    searchEdit.setText("");//this method maybe triggered edittext's textChangelistener
                    switchSearchType(Constants.SEARCH_BY_ISBN);
                    exchangeButton.setVisibility(View.GONE);
                    bindData(result);
                }
            }
        }.start();
    }

    protected void bindData(BaseResponse response) {
        if (response.success) {
            addDataToList(response);
            if (adapter!=null) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    private void addDataToList(BaseResponse response) {
        if (mSearchType==Constants.SEARCH_BY_KEYWORD){
            SearchBookListResponse resp = (SearchBookListResponse) response;
            adapter.clear();
            adapter.append(resp.data.books);
        }else if (mSearchType==Constants.SEARCH_BY_ISBN){
            SearchBookResponse resp = (SearchBookResponse)response;
            adapter.clear();
            adapter.append(resp.data);
        }
        adapter.notifyDataSetChanged();
    }


}
